import flash.events.Event;

class Main extends flash.display.MovieClip
{
	static var app:String="/video";
	var nc:flash.net.NetConnection;
	var videos:fl.controls.List;
	var logOutput:fl.controls.TextArea;

	public function new()
	{
		super();
		createView();
		nc = new flash.net.NetConnection();
		nc.client=this;
		nc.objectEncoding = 0;
		nc.addEventListener(flash.events.AsyncErrorEvent.ASYNC_ERROR, onAsyncError);
		nc.addEventListener(flash.events.NetStatusEvent.NET_STATUS, onStatus);
		
		addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
	}
	function onAddedToStage(event:Event)
	{
		removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
		var uri = getUri();
		log("connecting to rtmp://" + uri);
		nc.connect("rtmp://"+uri);
	}
	function onAsyncError(event:flash.events.AsyncErrorEvent):Void
	{
		log("nc async) text="+event.text+", error=" + event.error);
	}
	
	function onStatus(event:flash.events.NetStatusEvent):Void
	{
		var msg = "nc status) code=" + event.info.code;
		if(event.info.description!=null) msg += ", description=" + event.info.description;
		log(msg);
		log("connected:"+nc.connected);
		if(event.info.code =='NetConnection.Connect.Success')
		{
			nc.call("getVideos", new flash.net.Responder(onResultOk, onResultError));
		}
	}

	function onResultOk(arr):Void
	{
		videos.dataProvider = new fl.data.DataProvider(arr);
	}
	function onResultError(obj):Void
	{
		log("nc result error)"+obj);
		for(i in Reflect.fields(obj))
			log([i,Reflect.field(obj, i)]);
	}
	function onVideoSelect(event)
	{
		addChild(new VideoPlayer(nc, event.target.selectedItem.name /*.split(".flv").join('') */, log));
	}
	function log(msg:Dynamic)
	{
		logOutput.text += formatDate(Date.now()) + " " + msg+"\n";
		logOutput.textField.scrollV = logOutput.textField.maxScrollV;
	}
	function formatDate(d:Date):String
	{
		var h:Dynamic = d.getHours();
		if(h<10) h="0"+h;
		var m:Dynamic = d.getMinutes();
		if(m<10) m="0"+m;
		return "[" + h + ":" + m + "]";
	}
	function createView()
	{
		logOutput = new fl.controls.TextArea();
		//logOutput.enabled=false;
		logOutput.width=1010;
		logOutput.height=200;
		addChild(logOutput);
		
		videos = new fl.controls.List();
		videos.labelField="name";
		videos.width=200;
		videos.height=500;
		videos.x=0;
		videos.y=logOutput.y+logOutput.height+10;
		videos.addEventListener(flash.events.Event.CHANGE, onVideoSelect);
		addChild(videos);
	}
	public static function main()
	{
		flash.Lib.current.addChild(new Main());
	}
	function getUri():String
	{
		var parameters:Dynamic = flash.Lib.current.loaderInfo.parameters;
		//trace(parameters);
		var u = Reflect.field(parameters, "uri");
		if(u!=null)
			return u;
		var h = Reflect.field(parameters, "host");
		var p = Reflect.field(parameters, "port");
		var a = Reflect.field(parameters, "app");
		return (h==null?"localhost":h) + (p==null?":1935":":"+p) + (a==null?app:a);
	}
}
